import shutil
import sys
import time
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta

import pandas as pd
from tqdm import tqdm
import os

time_format = "UTC=%Y-%m-%dT%H:%M:%S.%f"
def get_file_paths(directory):
    file_paths = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            file_paths.append(os.path.normpath(file_path))
    return file_paths

beginDate = datetime.strptime("2025-03-12","%Y-%m-%d")
endDate = datetime.strptime("2025-04-17","%Y-%m-%d")
dataType = 1
dataPOEDir = "../dataset/dataPOE/Finish/"
dataMOEDir = "../dataset/dataMOE/Finish/"
dataPOEORBDir = "../dataset/dataPOEORB/"
dataMOEORBDir = "../dataset/dataMOEORB/"

lastDate = ""

if __name__ == "__main__":
    if dataType == 0:
        filePaths= get_file_paths(dataPOEDir)
        if os.path.exists(dataPOEORBDir):
            shutil.rmtree(dataPOEORBDir)
        if not os.path.exists(dataPOEORBDir):
            os.makedirs(dataPOEORBDir)
    else:
        filePaths= get_file_paths(dataMOEDir)
        if os.path.exists(dataMOEORBDir):
            shutil.rmtree(dataMOEORBDir)
        if not os.path.exists(dataMOEORBDir):
            os.makedirs(dataMOEORBDir)

    t_bar = tqdm(filePaths,total=len(filePaths))

    for filePath in t_bar:
        fileNameO = filePath.split('_')[-2].split('T')[0]
        # fileNameO = filePath.split('_')[6].split('T')[0]

        fileDate = datetime.strptime(fileNameO,"%Y%m%d")
        start_time = fileDate
        end_time = start_time + timedelta(hours=23, minutes=59, seconds=59)
        if start_time < beginDate or start_time > endDate:
            continue
        fileNameN = start_time.strftime("%Y-%m-%d")
        t_bar.set_description(f"{fileNameN}")

        tree = ET.parse(filePath)
        root = tree.getroot()
        dateRes = []
        # 解析 XML 中的每个 OSV
        for osv in root.findall('.//OSV'):
        # for osv in root.findall('.//Data_Block/List_of_OSVs/OSV'):

            utc_time = osv.find('UTC').text
            # 提取日期部分 (格式: 2023-12-31)
            date_str = utc_time.split('=')[1].split('T')[0]
            # 提取各个数据项
            utc = osv.find('UTC').text
            x = osv.find('X').text
            y = osv.find('Y').text
            z = osv.find('Z').text
            vx = osv.find('VX').text
            vy = osv.find('VY').text
            vz = osv.find('VZ').text

            x = float(x)*1000
            y = float(y)*1000
            z = float(z)*1000
            vx = float(vx)*1000
            vy = float(vy)*1000
            vz = float(vz)*1000

            dateNow = datetime.strptime(utc, time_format)
            if (dateNow.hour * 60 + dateNow.minute) % 5 != 0 or dateNow.second != 2:
                continue
            if dateNow < start_time or dateNow > end_time:
                continue

            dateRes.append([dateNow,x,y,z,vx,vy,vz])


        # writePath = f"../dataset/dataPOEORB/{fileNameN}.csv"
        if dataType == 0:
            writePath = f"{dataPOEORBDir}{fileNameN}.csv"
        else:
            writePath = f"{dataMOEORBDir}{fileNameN}.csv"
        df = pd.DataFrame(dateRes, columns=["date", "X", "Y", "Z", "VX", "VY", "VZ"])
        df['date'] = pd.to_datetime(df['date'])
        df.to_csv(writePath, index=False)


